package com.dianrui.operation.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.operation.Constant;
import com.dianrui.operation.MyApplication;
import com.dianrui.operation.R;
import com.dianrui.operation.dialog.FlycoDialog.UpdateAppDialog;
import com.dianrui.operation.interfaces.OnAskDialogCallBack;
import com.dianrui.operation.okhttp.XHttpRequest;

import com.dianrui.operation.update.DownloadProssDialog;
import com.dianrui.operation.update.DownloadService;
import com.dianrui.operation.util.BitmapUtils;
import com.dianrui.operation.util.ConvertUtils;
import com.dianrui.operation.util.GlideUtil;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.ExitDialog;
import com.google.gson.JsonObject;


import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;


public class SettingsActvity extends BaseActivity {
    private int progress;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.ver)
    TextView ver;
    @BindView(R.id.pic)
    ImageView pic;

    @Override
    public int getContentViewId() {
        return R.layout.setting;
    }

    @Override
    public void initView() {
        title.setText(getString(R.string.settings_txt));
        StringBuilder versionNameBulider=new StringBuilder();
        versionNameBulider.append("版本:").append(MyUtil.getAppVersionName(SettingsActvity.this));
        ver.setText(versionNameBulider.toString());

        if(!StringUtils.isEmpty(spUtils.getString("face"))){
            GlideUtil.loadUserImageViewSize(getApplicationContext(), spUtils.getString("face"), pic);
        }
    }

    @Override
    public void initData() {
    }


    @OnClick({R.id.back, R.id.click1, R.id.click2, R.id.click_3, R.id.click_4,R.id.click_5,R.id.click_6, R.id.logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.click1:
                JumpActivitys(AuthInfoActivity.class);
                break;
            case R.id.click2:
                JumpActivitys(ShowPdfActivity.class);
                break;
            case R.id.click_3:
                callPhone("4006801121");
                break;
            case R.id.click_4:
                showLoadingDialog("正在检查最新版本..");
                UpdateApp();
                break;
            case R.id.click_5:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(SettingsActvity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        choosePicUserImage();
                    } else {
                        ActivityCompat.requestPermissions(SettingsActvity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    choosePicUserImage();
                }
                break;
            case R.id.click_6:
                JumpActivitys(ForgetLoginPwd.class);
                break;
            case R.id.logout:
                ExitDialog.createExitDialog(SettingsActvity.this, getString(R.string.login_out_txt), new OnAskDialogCallBack() {
                    @Override
                    public void onokey(Dialog dialog) {
                        dialog.dismiss();
                        spUtils.clear();
                        startActivity(new Intent(SettingsActvity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                        finish();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                    }
                });
                break;

            default:
                break;
        }
    }

    private void UpdateApp() {
        XHttpRequest.getInstance().getRequest(Constant.UPDATEURL + MyUtil.getVersionName() + "/apply_type/1", new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) throws JSONException {
                if (!StringUtils.isEmpty(result)) {
                    JSONObject jsonObject = new JSONObject(result);
                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                        dismissLoadingDialog();
                        String explain=jsonObject.optJSONObject("data").optString("explain");
                        String title=jsonObject.optJSONObject("data").optString("title");
                        final String store_url=jsonObject.optJSONObject("data").optString("store_url");
                        final String isUpdate=jsonObject.optJSONObject("data").optString("is_update");
                        UpdateAppDialog.createStartCarDialog(SettingsActvity.this, title, explain, isUpdate,new OnAskDialogCallBack() {
                            @Override
                            public void onokey(Dialog dialog) {
                                dialog.dismiss();
                                update(store_url);
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();

                            }
                        });
                    }else {
                        dismissLoadingDialog();
                        ToastUtil.showToast(jsonObject.optString("message"));
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(result);
            }
        });
    }


    public void callPhone(String phoneNum) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(SettingsActvity.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4006801121"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                ActivityCompat.requestPermissions(SettingsActvity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4006801121"));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    //选择拍照或者相册选图
    private void choosePicUserImage() {
        MyUtil.createPhotoChooseDialog(0, 1, SettingsActvity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
            @Override
            public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                if (resultList == null && resultList.size() == 0) {
                    ToastUtil.showToast("照片未选中");
                    return;
                }
                GlideUtil.loadUserImageViewSize(getApplicationContext(), resultList.get(0).getPhotoPath(), pic);
                showLoadingDialog("正在上传头像中...");
                setInfoFace(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight())));

         }


            private void setInfoFace(String value) {
                showLoadingDialog("正在上传头像中...");
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
                jsonObject.addProperty("face", value);
                XHttpRequest.getInstance().postRequests(SharedUtil.getUrl()+Url.SETINFO, jsonObject.toString(),  new XHttpRequest.XCallBack() {
                    @Override
                    public void onResponse(String result) {
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                final JSONObject jsonObject = new JSONObject(result);
                                if (null != jsonObject &&!isFinishing()) {
                                    if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                        dismissLoadingDialog();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                        spUtils.put("face", jsonObject.optJSONObject("data").optString("face"));
                                        GlideUtil.loadUserImageViewSize(getApplicationContext(), jsonObject.optJSONObject("data").optString("face"), pic);

                                    } else {
                                        dismissLoadingDialog();
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void failedRequest(String result) {
                        dismissLoadingDialog();
                        ToastUtil.showToast(getString(R.string.net_error));
                    }
                });
            }

            @Override
            public void onHanlderFailure(int requestCode, String errorMsg) {
            }
        });
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    callPhone("4006801121");
                }
                break;

            default:
                break;
        }

    }


    private DownloadProssDialog downloadProssDialog;
    DownloadService downloadService;
    DownloadService.LocalBinder localBinder;
    private int isException = 0;

    private void update(String apkPath) {
        LogUtils.e("apkpath==" + apkPath);
        if (null == downloadProssDialog) {
            downloadProssDialog = new DownloadProssDialog(this, R.style.RcDialog);
        }
        downloadProssDialog.show();
        downloadProssDialog.setProgress(0, "连接服务器中,请等待...");
        Intent intent = new Intent(this, DownloadService.class);
        intent.setAction(DownloadService.ACTION_UPDATE);
        intent.putExtra(DownloadService.EXTRA_APK_PATH, apkPath);
        startService(intent);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }


    private final ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
            downloadService = ((DownloadService.LocalBinder) binder).getService();
            localBinder = (DownloadService.LocalBinder) binder;
            listenProgress();
        }

        public void onServiceDisconnected(ComponentName arg0) {
            downloadService = null;
        }
    };

    boolean flag = true;

    void listenProgress() {
        Observable.interval(100, TimeUnit.MILLISECONDS)
                .takeWhile(new Func1<Long, Boolean>() {
                    @Override
                    public Boolean call(Long aLong) {
                        return localBinder.getProgress() <= 100 && flag;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.e("onCompleted");
                        LogUtils.e(localBinder.getDownloadExceptionInfo());
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("onError==" + e.toString());
                    }

                    @Override
                    public void onNext(final Object aLong) {
                        progress = localBinder.getProgress();
                        LogUtils.e("当前app下载进度:" + progress);
                        if (progress < 100 && progress >= 0) {
                            if (null != downloadProssDialog) {
                                //pd.setMessage("正在下载中 : " + progress + "%");
                                downloadProssDialog.show();
                                downloadProssDialog.setProgress(progress, "正在下载中...");
                            }
                        } else if (progress >= 100) {
                            flag = false;
                            LogUtils.e("下载完成" + flag);
                            dismissDialog();
                        }else if (progress == -100) {
                            dismissDialog();
                            if (isException == 0) {
                                isException++;
                                Log.e("localBinder异常",localBinder.getDownloadExceptionInfo());
                                ToastUtil.showToast(localBinder.getDownloadExceptionInfo());
                            }
                        }


                    }
                });
    }

    private void dismissDialog() {
        if (null != downloadProssDialog) {
            downloadProssDialog.dismiss();
            localBinder.setDownloadEnd();
            downloadProssDialog = null;
        }
        unbindService(mConnection);
    }
}
